<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Open Source Web Animation - C++ Tutorial: Object Slicing and Virtual Table</title>
  <meta
 content="Open Source Web Animation C++ Tutorial: Object Slicing and Virtual Table"
 name="description" />
  <meta
 content="Open Source, Web Animation, C++ Tutorial, Object Slicing, Virtual Table"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>
<br />
<br />
<br />
<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial<br />Object Slicing and Virtual Table</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>   
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />
<br />
<img src="images/slicing/SumJeenKang.png" alt="SumJeenKang"/>
<br />
<br />

<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="slicing">Object Slicing</div>
<p>When a derived class object is <strong>passed by value</strong> as a <strong>base class object (Base derived_obj)</strong>, the base class <strong>copy constructor</strong> is called. So, the specific behaviors of a derived class object are <strong>sliced off</strong>. We're left with a base class object. In other words, if we <strong>upcast</strong> to an <strong>object</strong> instead of a <strong>pointer</strong> or <strong>reference</strong>, the object is <strong>sliced</strong>. As a result, all that remains is the subobject that corresponds to the destination type of your cast.</p>
<p>This is not surprising because a base class constructor created it. This is called <strong>object slicing</strong>. This is one of the reason we should prefer <strong>pass-by-reference</strong> to pass-by-value.</p>
<p>Here is the example of object slicing.</p>
<pre>
#include &lt;iostream&gt;
#include &lt;string&gt;

using namespace std;

class Animal{
public:
	Animal(const string& s) : name(s) {}
	virtual void eat() const {
		cout << "animal: " << name << " eat()" << endl;
	}
private:
	string name;
};

class Bird : public Animal {
private:
	string name;
	string habitat;
public:
	Bird(const string& sp, const string &s, const string &h)
		: Animal(sp), name(s), habitat(h) {};
	virtual void eat() const {
		cout << "bird: " << name << " eat() in " << habitat << endl;
	}
};

void WhatAreYouDoing(<font color="blue">Animal a</font>) {
	a.eat();
}

void WhatAreYouDoingReference(<font color="blue">const Animal &a</font>) {
	a.eat();
}

int main()
{
	Animal animal("Animal");
	Bird bird("Eagle","Bald","US and Canada");

	cout << "pass-by-value" << endl;
	WhatAreYouDoing(animal);
	WhatAreYouDoing(bird);

	cout << "\npass-by-reference" << endl;
	WhatAreYouDoingReference(animal);
	WhatAreYouDoingReference(bird);
}
</pre>
<p>Output of the run is:</p>
<pre>
pass-by-value
animal: Animal eat()
animal: Eagle eat()

pass-by-reference
animal: Animal eat()
bird: Bald eat() in US and Canada
</pre>
<p>The virtual function <strong>eat()</strong> is passed an object of type <strong>Animal</strong> and <strong>by value</strong>. We might expect the first call to produce <strong>animal: Animal eat()</strong>, and the second to produce <strong>bird: Bald eat() in US and Canada</strong>. In fact, both calls use the base-class version of <strong>eat</strong>.</p>
<p>What happened? <br />
Because <strong>eat( )</strong> accepts an Animal <strong>object</strong> (rather than a pointer or reference), any calls to eat( ) will cause an object the size of <strong>Animal</strong> to be pushed on the stack and cleaned up after the call. This means that if an object of a class inherited from <strong>Animal</strong> is passed to <strong>eat( )</strong>, the compiler accepts it, but it copies only the <strong>Animal</strong> portion of the object. It <strong>slices</strong> the derived portion off of the object.</p>
<p>How about the virtual function call?<br />
<strong>Bird::eat( )</strong> makes use of portions of both <strong>Animal</strong> (which still exists) and <strong>Bird</strong>, which no longer exists because it was sliced off! So what happens when the virtual function is called?</p>
<p>Because the object is being passed by value, the compiler knows the precise type of the object because the derived object has been forced to become a base object. When passing by value, the copy-constructor for a <strong>Animal</strong> object is used, which initializes the <strong>vptr</strong> (virtual table pointer) to the Animal <strong>vtbl</strong> (virtual table) and copies only the <strong>Animal</strong> parts of the object. There's no explicit copy-constructor here, so the compiler somehow makes one. The <strong>Bird</strong> object losing all the things make it bird-like becomes an <strong>Animal</strong> during slicing.</p>
<p>The second output which used <strong>pass-by-reference</strong> is what we expected.</p>
<br />
<br />
<div class="subtitle" id="vtbl">Virtual Table and Virtual Pointer</div>
<p>The way compilers handle virtual functions is to add a hidden member to each object. The hidden member holds a pointer to an array of function addresses. Such an array is usually termed a <strong>virtual function table(vtbl)</strong>. The vtbl holds the addresses of the virtual functions declared for objects of that class.</p>
<p> An object of a base class, for example, contains a pointer to a table of addresses of all the virtual functions for that class. An object of a derived class contains a pointer to a separate table of addresses. If the derived class provides a new definition of a virtual function, the <strong>vtbl</strong> holds the address of the new function. If the derived class doesn't redefine the virtual function, the <strong>vtbl</strong> holds the address of the original version of the function. If the derived class defines a new function and makes it virtual, its address is added to the <strong>vtbl</strong>. So, whether we define 1 or 100 virtual functions for a class, we are adding just one address member to an object. </p>
<p>When we call a virtual function, the program looks at the <strong>vtbl</strong>  address stored in an object and goes to the corresponding table of function addresses. If we use the first virtual function defined in the class declaration, the program uses the first function address in the array and execute the function that has that address, and so on.</p>
<ul>
	<li>Each object has its size increased by the amount needed to hold that address.</li>
	<li>For each class, the compiler creates a table of addresses of virtual functions.</li>
	<li>For each function call, there's an extra step of going to a table to look up an address. </li>
</ul> 
<br />
<p>In summary, virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed first which creates the vtable. If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions</p>
<br />

<p>Even though virtual functions provide dynamic binding, we need implement them judiciously. Scott Meyers said (in his book "Effective C++"), "The bottom line is that gratuitously declaring all destructors virtual is just as wrong as never declaring them virtual. In fact, many people summarize the situation this way: declare a virtual destructor in a class if and only if that class contains at least on virtual function." </p>

<br />
<br />
<img src="images/slicing/JungSun.png" alt="JungSun"/>
<br />
<br />

<br />
<br />

<div id="rightpanel">
<div align="center">
</div></div>

<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />



<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
